package com.github.ghsea.sso.client.security.cas;

import com.github.ghsea.sso.client.config.ShiroConfig;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author guhai
 */
@SuppressWarnings("ALL")
@Component(value = "casFilter")
public class CasFilterExt extends CasFilter {

    private Logger log = LoggerFactory.getLogger(CasFilterExt.class);

    @Autowired
    private ShiroConfig shiroConfig;

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        WebUtil.saveOriginUrl(request);
        return super.createToken(request, response);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        Optional<String> originUrl = WebUtil.getOriginUrl();
        if (originUrl.isPresent()) {
            redirectToOriginUrl(request, response, originUrl.get());
            return false;
        } else {
            return super.onLoginSuccess(token, subject, request, response);
        }
    }

    private void redirectToOriginUrl(ServletRequest request, ServletResponse response, String originUrl) throws IOException {
        HttpServletResponse rep = (HttpServletResponse) response;
        String redirectUrl = originUrl;
        if (!redirectUrl.startsWith("https") && !redirectUrl.startsWith("http")) {
            log.warn("there is no protocol in the redirect url.Use http as default.");
            redirectUrl = "http://" + redirectUrl;
        }

        rep.sendRedirect(rep.encodeRedirectURL(redirectUrl));
        WebUtil.clearOriginUrl(request);
    }

    @Autowired
    public void setFailureUrl() {
        super.setFailureUrl(shiroConfig.getCasServerUrl() + "/login");
    }

}
